"""
cron任务
每3分钟执行一次
"""
import logging
from datetime import datetime, timedelta

from django.core.management.base import BaseCommand

from biz.core.thanos.models import WorkOrder
from biz.const import WorkOrderStatus, ProblemType, UserStatus
from biz.core.thanos.services import work_order_service
from gis.admin.models import User

_LOGGER = logging.getLogger(__name__)

"""
    将2小时以内未分配的工单（充值申诉除外），分配给在线客服
"""


def assign_customer():
    _LOGGER.info('start assign customer')
    pre_time = datetime.now() - timedelta(hours=2)
    orders = WorkOrder.objects.filter(status=WorkOrderStatus.WAITING).filter(created_at__gte=pre_time).excute(
        type_id=ProblemType.RECHARGE).all()
    if orders:
        for order in orders:
            pro_id = order.pro_id
            handler_id = work_order_service.assign_customer(pro_id)
            if handler_id:
                order.handler_id = handler_id
                order.save()
    _LOGGER.info('end assign customer')


"""
    自动更改客服状态，如果 半小时没有对工单的操作 将状态改为休息
"""


def check_customer_status():
    _LOGGER.info('start change customer status')
    users = User.objects.filter(deleted=False).filter(status=UserStatus.WORKING).all()
    pre_time = datetime.now() - timedelta(minutes=30)
    for user in users:
        if WorkOrder.objects.filter(handler_id=user.id).filter(updated_at__gte=pre_time).count():
            user.status = UserStatus.REST
            user.save()
    _LOGGER.info('end change customer status')


def start():
    assign_customer()
    check_customer_status()


class Command(BaseCommand):

    def handle(self, **kwargs):
        start()
